# -*- coding: UTF-8 -*-
import paramiko
from scp import SCPClient

def execute_remote_command(host, port, username, password, command):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()

    # 允许自动添加主机到已知主机列表
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程服务器
        ssh.connect(host, port=port, username=username, password=password, timeout=10,
                    allow_agent=False, look_for_keys=False)

        # 执行命令并获取输出
        stdin, stdout, stderr = ssh.exec_command(command)

        # 获取命令执行结果（标准输出和标准错误）
        output = stdout.read().decode('utf-8').strip()
        error = stderr.read().decode('utf-8').strip()
        if error != "":
            print(f"Error during execution:\n{error} host: {host}")
            return output, error

        # 关闭连接
        ssh.close()

        return output, error

    except paramiko.AuthenticationException as e:
        print(f"Authentication failed: {e} host: {host}")
    except paramiko.SSHException as e:
        print(f"SSH connection error: {e} host: {host}")
    except Exception as e:
        print(f"An unexpected error occurred: {e} host: {host}")
        
def create_ssh_client(hostname, port, username, password):
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname, port, username, password)
    return ssh

def push_file_via_scp(local_file_path, remote_file_path, linux_host, linux_port, username, password):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到Linux服务器
        ssh.connect(hostname=linux_host, port=linux_port, username=username, password=password)
        
        # 使用SFTP传输文件
        sftp = ssh.open_sftp()
        sftp.put(local_file_path, remote_file_path)
        sftp.close()
        
        print(f"File {local_file_path} uploaded successfully to {remote_file_path}")
    except Exception as e:
        print(f"Failed to upload file: {e} host: {linux_host}")
    finally:
        ssh.close()

def get_file_via_scp(remote_file_path, local_file_path, linux_host, linux_port, username, password):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到Linux服务器
        ssh.connect(hostname=linux_host, port=linux_port, username=username, password=password)
        
        # 使用SFTP传输文件
        scp = SCPClient(ssh.get_transport())
        scp.get(remote_file_path, local_file_path)
        
        print(f"File {remote_file_path} downloaded successfully to {local_file_path}")
    except Exception as e:
        print(f"Failed to download file: {e}")
    finally:
        ssh.close()
        scp.close()

# # 使用示例
# host = "172.16.111.84"
# port = 22  # 默认SSH端口
# username = "root"
# password = "hyzk2o2o"
# command = "ls"

# output, error = execute_remote_command(host, port, username, password, command)

# if error:
#     print(f"Error during execution:\n{error}")
# else:
#     print(f"Command output:\n{output}")